"""图片上传接口"""
import os
import uuid
from flask import Blueprint, request, jsonify, current_app
from werkzeug.utils import secure_filename

upload_bp = Blueprint('upload', __name__, url_prefix='/api')

# 确保上传文件夹存在
def ensure_upload_folder():
    upload_folder = current_app.config['UPLOAD_FOLDER']
    # 确保上传目录存在
    if not os.path.exists(upload_folder):
        os.makedirs(upload_folder, exist_ok=True)
    # 记录上传路径用于调试
    current_app.logger.info(f"文件上传目录: {os.path.abspath(upload_folder)}")

@upload_bp.route('/upload', methods=['POST'])
def upload_file():
    """图片上传接口"""
    # 确保上传文件夹存在
    ensure_upload_folder()
    
    if 'file' not in request.files:
        return jsonify({
            "code": -1,
            "msg": "没有文件部分"
        }), 400
    
    file = request.files['file']
    
    if file.filename == '':
        return jsonify({
            "code": -1,
            "msg": "没有选择文件"
        }), 400
    
    if file:
        # 生成唯一文件名
        ext = os.path.splitext(file.filename)[1].lower()
        # 限制文件类型
        allowed_extensions = {'.png', '.jpg', '.jpeg', '.webp', '.gif'}
        if ext not in allowed_extensions:
            return jsonify({
                "code": -1,
                "msg": "不支持的文件类型"
            }), 400
            
        filename = f"{uuid.uuid4()}{ext}"
        upload_folder = current_app.config['UPLOAD_FOLDER']
        filepath = os.path.join(upload_folder, filename)
        
        # 保存文件
        try:
            file.save(filepath)
            
            # 验证文件是否真的保存成功
            if not os.path.exists(filepath):
                raise Exception(f"文件保存失败，路径: {filepath}")
                
            # 构建正确的文件URL
            # 使用相对路径而非绝对路径，避免跨域问题
            file_url = f"/api/uploads/{filename}"
            
            current_app.logger.info(f"文件上传成功: {filepath}")
            return jsonify({
                "code": 0,
                "data": {
                    "url": file_url
                }
            })
        except Exception as e:
            current_app.logger.error(f"文件保存失败: {str(e)}")
            return jsonify({
                "code": -1,
                "msg": "文件保存失败"
            }), 500
    
    return jsonify({
        "code": -1,
        "msg": "文件上传失败"
    }), 500